//
//  HttpRequest.m
//  XiaoHongShu
//
//  Created by Jason on 2022/6/18.
//

#import "HttpRequest.h"
#import "HttpResponseModel.h"

@implementation HttpRequest

#pragma mark - 网络单例
+(instancetype)shareInstance {
    static HttpRequest *httpRequest;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //设置网络会话配置
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置网络超时时间
        configuration.timeoutIntervalForRequest = 2000;
        httpRequest = [[self alloc]initWithBaseURL:[NSURL URLWithString:kBaseUrlString] sessionConfiguration:configuration];
    });
    return httpRequest;
}


#pragma mark - 重写 initWithBaseURL：方法设置请求或响应内容
- (instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration {
    if (self = [super initWithBaseURL:url sessionConfiguration:configuration]) {
        //设置请求序列化器
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        //设置响应序列化器
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //设置请求的内容样式
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"text/xml",@"application/x-www-form-urlencoded", nil];
        
        //设置请求头
        //self.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"
    }
    return  self;
}

#pragma mark - post 请求
-(NSURLSessionDataTask *)post:(NSString *)urlString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask * _Nonnull, HttpResponseModel * _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nonnull, NSError * _Nonnull))failure {
    
    return [self POST:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        //直接将 post 请求返回的 response 数据转成模型
        HttpResponseModel *responseModel = [HttpResponseModel yy_modelWithDictionary:responseObject];
        success(task, responseModel);  //执行success block
    } failure:failure];
}

#pragma mark - get 请求
- (NSURLSessionDataTask *)get:(NSString *)urlString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask * _Nonnull, HttpResponseModel * _Nonnull))success failure:(void (^)(NSURLSessionDataTask * _Nonnull, NSError * _Nonnull))failure {
    //重新调用父类 AFHTTPSessionManager 的 GET 方法
    return [self GET:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        //直接将请求成功返回的 responseObject 字典数据转换成 模型
        HttpResponseModel *responseModel = [HttpResponseModel yy_modelWithDictionary:responseObject];
        success(task, responseModel);  //执行 succes block
    } failure:failure];
}

@end
